package main

import (
	"context"
	"fmt"
	"golang.org/x/sync/semaphore"
	"time"
)

func main() {

}

func testSemaphore() {
	ctx := context.Background()
	sem := semaphore.NewWeighted(5) // 总权重为5

	// 模拟需要不同权重的任务
	tasks := []Task{
		{Name: "Task 1", Weight: 2},
		{Name: "Task 2", Weight: 3},
		{Name: "Task 3", Weight: 1},
		{Name: "Task 4", Weight: 4},
	}

	for _, t := range tasks {
		go func(taskName string, w int64) {
			if err := sem.Acquire(ctx, w); err != nil { // 获取权重
				fmt.Printf("Failed to acquire semaphore: %v\n", err)
				return
			}
			defer sem.Release(w) // 释放权重

			fmt.Printf("Start %s (weight: %d)\n", taskName, w)
			time.Sleep(2 * time.Second)
			fmt.Printf("Finish %s\n", taskName)
		}(t.Name, t.Weight)
	}

	time.Sleep(10 * time.Second) // 等待所有任务完成
}

type Task struct {
	Name   string
	Weight int64
}
